#!/bin/sh

## 1. 手动编辑书籍
## 2. /usr/local/bin/formatboottoline, 生成 readperday文件，mdfile.OK 文件记录每一章的阅读量
## 3. /usr/local/bin/genreadcal, 通过 readperday 文件，生成脚本 readcal
## 4. 合并 mdfile  readcal

if [ $# -ne 4 ]; then
	echo "usage: $0 mdfile stardate tag wordsperday"
	exit
fi

mdfile=$1

# 检测tag是否用过

if [ -e config ];then
	source config
else
	tag=$3
	grep -q -w $tag ../tag.md
	if [ $? -eq 0 ]; then
		echo "TAG 已经存在"
		exit -1
	else
		echo $tag >> ../tag.md
	fi
fi

# 替换不能不能处理符号：%&`

sed -e "s/%/perperper/g" $mdfile  | sed -e "s/\`/backbackquotequote/g" | sed -e "s/\"/“/g" | sed -e "s/\[/\\[/g" | sed -e "s/\]/\\]/g" | sed -e "s/&/andandandand/g" >copy.md

mdfile=copy.md

allwords=`wc $mdfile |awk '{print $3}'`

allwordsinchinese=$(expr $allwords / 3)

echo $4 |grep "天" >/dev/null

if [ $? -eq 0 ]; then 
	daystoread=`echo $4|sed -e "s/天//"`
	wordsperday=$(expr $allwords / $daystoread)
else
	wordsperday=$4
fi

rm -f $tag*.md

awk '{printf $0 "XXXX" }' $mdfile| sed -e "s/XXXX#### /XXXX\n#### /g" | sed -e "s/^/echo \"/" | sed -e "s/$/\"\>/" >$mdfile.OK

echo "" >>$mdfile.OK

# 计算每行的阅读天数

awk -v words=$wordsperday '{printf "%d\n", length($0)/words}' $mdfile.OK  | awk '{if ($1=="0"){ printf "1+"} else {printf $0 "+"}}'  | sed -e "s/+$//" >bc.file

# awk -v words=$4 '{printf "7\n"}' $mdfile.OK  | awk '{if ($1=="0"){ printf "1+"} else {printf $0 "+"}}'  | sed -e "s/+$//" >bc.file

readday=`bc < bc.file`

bookname=`pwd | awk -F/ '{print $NF}' |sed -e "s/[1234567890]//g"`

echo $bookname "共" $allwordsinchinese "字，阅读" $readday "天"

sed -e "s/+/\n/g" bc.file >readperday


number=`wc $mdfile.OK|awk '{print $1}'`

no $number  >no

genreadcal $2 $3 

sed -e "s/.md/-$bookname.md/g" readcal > readcal.tmp

mv readcal.tmp  readcal

paste $mdfile.OK readcal >1.sh

sh 1.sh

rm -f bc.file no readcal readperday $mdfile.OK 1.sh

for files in `ls -l $tag*.md |sed -e "/^l/d"|awk '{print $NF}'`

do

	cat $files |sed -e "s/XXXX/\n/g" >tmp.md

	sed -e "s/perperper/%/g" tmp.md |sed -e "s/backbackquotequote/\`/g" | sed -e "s/andandandand/&/g" >$files

done

rm tmp.md

echo "统计用字频率"

countword $mdfile

upconfig

genindex

genrichindex

gencal

adday

echo "生成大事记"

getevent $mdfile

echo "生成引用书单"

getbooks $mdfile

genbrief

touch BOOKLIST.md

touch timetag

touch $tag*.md

markread 

rm -f copy.md